home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / POV-Ray 3.0.2 / src / SOURCE / LIBPNG / LIBPNG.TXT < prev    next >
Encoding:
Text File  |  1996-11-07  |  59.4 KB  |  1,321 lines  |  [TEXT/ttxt]

  1. libpng.txt - a description on how to use and modify libpng
  2.  
  3.     libpng 1.0 beta 3 - version 0.89
  4.     Updated and distributed by Andreas Dilger <adilger@enel.ucalgary.ca>,
  5.        based on:
  6.  
  7.     libpng 1.0 beta 2 - version 0.88
  8.     For conditions of distribution and use, see copyright notice in png.h
  9.     Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  10.     May 24, 1996
  11.     Updated/rewritten per request in the libpng FAQ
  12.     Copyright (c) 1995 Frank J. T. Wojcik
  13.     December 18, 1995 && January 20, 1996
  14.  
  15. I. Introduction
  16.  
  17. This file describes how to use and modify the PNG reference library
  18. (known as libpng) for your own use.  There are five sections to this
  19. file: introduction, structures, reading, writing, and modification and
  20. configuration notes for various special platforms.  In addition to this
  21. file, example.c is a good starting point for using the library, as
  22. it is heavily commented and should include everything most people
  23. will need.
  24.  
  25. Libpng was written as a companion to the PNG specification, as a way
  26. to reduce the amount of time and effort it takes to support the PNG
  27. file format in application programs.  Most users will not have to
  28. modify the library significantly; advanced users may want to modify it
  29. more.  All attempts were made to make it as complete as possible,
  30. while keeping the code easy to understand.  Currently, this library
  31. only supports C.  Support for other languages is being considered.
  32.  
  33. Libpng has been designed to handle multiple sessions at one time,
  34. to be easily modifiable, to be portable to the vast majority of
  35. machines (ANSI, K&R, 16 bit, 32 bit) available, and to be easy to
  36. use.  The ultimate goal of libpng is to promote the acceptance of
  37. the PNG file format in whatever way possible.  While there is still
  38. work to be done (see the pngtodo.txt file), libpng should cover the
  39. majority of the needs of it's users.
  40.  
  41. Libpng uses zlib for its compression and decompression of PNG files.
  42. The zlib compression utility is a general purpose utility that is
  43. useful for more than PNG files, and can be used without libpng.
  44. See the documentation delivered with zlib for more details.
  45.  
  46. Libpng is thread safe, provided the threads are using different
  47. instances of the structures.  Each thread should have its own
  48. png_struct and png_info instances, and thus its own image.
  49. Libpng does not protect itself against two threads using the
  50. same instance of a structure.
  51.  
  52.  
  53.  
  54. II. Structures
  55.  
  56. There are two main structures that are important to libpng, png_struct
  57. and png_info.  The first, png_struct, is an internal structure that
  58. will not, for the most part, be used by a user except as the first
  59. variable passed to every libpng function call.
  60.  
  61. The png_info structure is designed to provide information about the
  62. png file.  All of its fields are intended to be examined or modified
  63. by the user.  See png.h for a good description of the png_info fields.
  64. png.h is also an invaluable reference for programming with libpng.
  65.  
  66. And while I'm on the topic, make sure you include the libpng header file:
  67.  
  68. #include <png.h>
  69.  
  70.  
  71.  
  72. III. Reading
  73.  
  74. Reading PNG files:
  75.  
  76. We'll now walk you through the possible functions to call when reading
  77. in a PNG file, briefly explaining the syntax and purpose of each one.
  78. See example.c and png.h for more detail.  While Progressive reading
  79. is covered in the next section, you will still need some of the
  80. functions discussed in this section to read a PNG file.
  81.  
  82. You will want to do the I/O initialization(*) before you get into libpng,
  83. so if it doesn't work, you don't have much to undo.  Of course, you
  84. will also want to insure that you are, in fact, dealing with a PNG
  85. file.  Libpng provides a simple check to see if a file is a PNG file.
  86. To use it, pass in the first 1 to 8 bytes of the file, and it will
  87. return true or false (1 or 0) depending on whether the bytes could be
  88. part of a PNG file.  Of course, the more bytes you pass in, the
  89. greater the accuracy of the prediction.
  90.  
  91. If you are intending to keep the file pointer open for use in libpng,
  92. you must ensure you don't read more than 8 bytes from the beginning
  93. of the file, and you also have to make a call to png_set_sig_bytes_read()
  94. with the number of bytes you read from the beginning.  Libpng will
  95. then only check the bytes (if any) that your program didn't read.
  96.  
  97. (*): If you are not using the standard I/O functions, you will need
  98. to replace them with custom functions.  See the discussion under
  99. Customizing libpng.
  100.  
  101.     FILE *fp = fopen(file_name, "rb");
  102.     if (!fp)
  103.     {
  104.         return;
  105.     }
  106.     fread(header, 1, number, fp);
  107.     is_png = png_check_sig(header, 0, number);
  108.     if (!is_png)
  109.     {
  110.         return;
  111.     }
  112.  
  113. Next, png_struct and png_info need to be allocated and initialized.
  114. In order to ensure that the size of these structures is correct even
  115. with a dynamically linked libpng, there are functions to initialize
  116. and allocate the structures.  We also pass the library version, and
  117. optionally pointers to error handling functions (these can be NULL
  118. if the default error handlers are to be used).  See the section on
  119. Changes to Libpng below regarding the old initialization functions.
  120.  
  121.     png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  122.        (void *)user_error_ptr, user_error_fn, user_warning_fn);
  123.     if (!png_ptr)
  124.         return;
  125.     png_infop info_ptr = png_create_info_struct(png_ptr);
  126.     if (!info_ptr)
  127.     {
  128.         png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  129.         return;
  130.     }
  131.     png_infop end_info = png_create_info_struct(png_ptr);
  132.     if (!end_info)
  133.     {
  134.         png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  135.         return;
  136.     }
  137.  
  138. The error handling routines passed to png_create_read_struct() are only
  139. necessary if you are not using the libpng supplied error handling
  140. functions.  When libpng encounters an error, it expects to longjmp back
  141. to your routine.  Therefore, you will need to call setjmp and pass the
  142. jmpbuf field of your png_struct.  If you read the file from different
  143. routines, you will need to update the jmpbuf field every time you enter
  144. a new routine that will call a png_ function.
  145.  
  146. See your documentation of setjmp/longjmp for your compiler for more
  147. information on setjmp/longjmp.  See the discussion on libpng error
  148. handling in the Customizing Libpng section below for more information on
  149. the libpng error handling.  If an error occurs, and libpng longjmp's
  150. back to your setjmp, you will want to call png_destroy_read_struct() to
  151. free any memory.
  152.  
  153.     if (setjmp(png_ptr->jmpbuf))
  154.     {
  155.         png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  156.         fclose(fp);
  157.         return;
  158.     }
  159.  
  160. Now you need to set up the input code.  The default for libpng is to
  161. use the C function fread().  If you use this, you will need to pass a
  162. valid FILE * in the function png_init_io().  Be sure that the file is
  163. opened in binary mode.  Again, if you wish to handle reading data in
  164. another way, see the discussion on libpng I/O handling in the Customizing
  165. Libpng section below.
  166.  
  167.     png_init_io(png_ptr, fp);
  168.  
  169. If you had previously opened the file and read any of the signature from
  170. the beginning in order to see if this was a PNG file, you need to let
  171. libpng know that there are some bytes missing from the start of the file.
  172.  
  173.     png_set_sig_bytes(png_ptr, number);
  174.  
  175. You are now ready to read all the file information up to the actual
  176. image data.  You do this with a call to png_read_info().
  177.  
  178.     png_read_info(png_ptr, info_ptr);
  179.  
  180. The png_info structure is now filled in with all the data necessary
  181. to read the file.  Some of the more important parts of the info_ptr are:
  182.  
  183.     width          - holds the width of the file
  184.     height         - holds the height of the file
  185.     bit_depth      - holds the bit depth of one of the image channels
  186.     color_type     - describes the channels and what they mean
  187.                      (see the PNG_COLOR_TYPE_ macros for more information)
  188.     channels       - number of channels of info for the color type
  189.     pixel_depth    - bits per pixel, the result of multiplying the 
  190.                      bit_depth times the channels
  191.     rowbytes       - number of bytes needed to hold a row
  192.     interlace_type - currently 0 for none, 1 for interlaced
  193.     signature      - holds the signature read from the file (if any).  The
  194.                      data is kept in the same offset it would be if the
  195.                      whole signature were read (ie if you had already read
  196.                      in 4 bytes of signature, the remaining 4 bytes would
  197.                      be in signature[4] through signature[7]).
  198.     valid          - this details which optional chunks were found in the
  199.                      file.  To see if a chunk was present, AND '&' valid with
  200.                      the appropriate PNG_INFO_<chunk name> define.
  201.  
  202. These are also important, but their validity depends on whether a
  203. corresponding chunk exists. Use valid (see above) to ensure that what
  204. you're doing with these values makes sense.
  205.  
  206.     palette        - the palette for the file (PNG_INFO_PLTE)
  207.     num_palette    - number of entries in the palette
  208.     gamma          - the gamma the file is written at (PNG_INFO_gAMA)
  209.     sig_bit        - the number of significant bits (PNG_INFO_sBIT)
  210.                      for the gray, red, green, and blue channels, whichever
  211.                      are appropriate for the given color type.
  212.     trans_values   - transparent pixel for non-paletted images (PNG_INFO_tRNS)
  213.     trans          - array of transparent entries for paletted images
  214.     num_trans      - number of transparent entries
  215.     hist           - histogram of palette (PNG_INFO_hIST)
  216.     mod_time       - time image was last modified (PNG_VALID_tIME)
  217.     background     - background color (PNG_VALID_bKGD)
  218.     text           - text comments in the file.
  219.     num_text       - number of comments
  220.  
  221. for more information, see the png_info definition in png.h and the
  222. PNG specification for chunk contents.  Be careful with trusting
  223. rowbytes, as some of the transformations could increase the space
  224. needed to hold a row (expand, RGBX, XRGB, gray_to_rgb, etc.).
  225. See png_update_info(), below.
  226.  
  227. A quick word about text and num_text.  PNG stores comments in
  228. keyword/text pairs, one pair per chunk.  While there are suggested
  229. keywords, there is no requirement to restrict the use to these
  230. strings.  There is a requirement to have at least one character for a
  231. keyword.  It is strongly suggested that keywords be sensible to humans
  232. (that's the point), so don't use abbreviations.  See the PNG
  233. specification for more details.  There is also no requirement to have
  234. text after the keyword.
  235.  
  236. Keywords should be limited to 80 characters without leading or trailing
  237. spaces, but non-consecutive spaces are allowed within the keyword.  It is
  238. possible to have the same keyword any number of times.  The text field
  239. is an array of png_text structures, each holding pointer to a keyword
  240. and a pointer to a text string.  Only the text string may be null.
  241. The keyword/text pairs are put into the array in the order that
  242. they are received.  However, some or all of the text chunks may be
  243. after the image, so, to make sure you have read all the text chunks,
  244. don't mess with these until after you read the stuff after the image.
  245. This will be mentioned again below in the discussion that goes with
  246. png_read_end().
  247.  
  248. After you've read the file information, you can set up the library to
  249. handle any special transformations of the image data.  The various
  250. ways to transform the data will be described in the order that they
  251. should occur.  This is important, as some of these change the color
  252. type and/or bit depth of the data, and some others only work on
  253. certain color types and bit depths.  Even though each transformation
  254. checks to see if it has data that it can do somthing with, you should
  255. make sure to only enable a transformation if it will be valid for the
  256. data.  For example, don't swap red and blue on grayscale data.
  257.  
  258. The colors used for the background and transparency values should be
  259. supplied in the same format/depth as the current image data.  They
  260. are stored in the same format/depth as the image data in a bKGD or tRNS
  261. chunk, so this is what libpng expects for this data.  The colors are
  262. transformed to keep in sync with the image data when an application
  263. calls the png_update_info() routine (see below).
  264.  
  265. Data will be decoded into the supplied row buffers packed into bytes
  266. unless the library has been told to transform it into another format.
  267. For example, 4 bit/pixel paletted or grayscale data will be returned
  268. 2 pixels/byte with the leftmost pixel in the high-order bits of the
  269. byte, unless png_set_packing() is called.  8-bit RGB data will be stored
  270. in RGBRGBRGB format unless png_set_filler() is called to insert filler
  271. bytes, either before or after each RGB triplet.  16-bit RGB data will
  272. be returned RRGGBBRRGGBB, with the most significant byte of the color
  273. value first, unless png_set_strip_16() is called to transform it to
  274. regular RGBRGB triplets.
  275.  
  276. The following code transforms grayscale images of less than 8 to 8 bits,
  277. changes paletted images to RGB, and adds a full alpha channel if there is
  278. transparency information in a tRNS chunk.  This is most useful on
  279. grayscale images with bit depths of 2 or 4 or if there is a multiple-image
  280. viewing application that wishes to treat all images in the same way.
  281.  
  282.    if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  283.       info_ptr->bit_depth < 8)
  284.         png_set_expand(png_ptr);
  285.  
  286.     if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY &&
  287.       info_ptr->bit_depth < 8)
  288.       png_set_expand(png_ptr);
  289.  
  290.    if (info_ptr->valid & PNG_INFO_tRNS)
  291.       png_set_expand(png_ptr);
  292.  
  293. PNG can have files with 16 bits per channel.  If you only can handle
  294. 8 bits per channel, this will strip the pixels down to 8 bit.
  295.  
  296.    if (info_ptr->bit_depth == 16)
  297.       png_set_strip_16(png_ptr);
  298.  
  299. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  300. they can, resulting in, for example, 8 pixels per byte for 1 bit
  301. files.  This code expands to 1 pixel per byte without changing the
  302. values of the pixels:
  303.  
  304.     if (info_ptr->bit_depth < 8)
  305.         png_set_packing(png_ptr);
  306.  
  307. PNG files have possible bit depths of 1, 2, 4, 8, and 16.  It is then
  308. required that values be "scaled" or "shifted" up to the bit depth used
  309. in the file (ie from 5 bits/sample in the range [0,31] to 8 bits/sample
  310. in the range [0, 255]).  However, they also provide a way to describe
  311. the true bit depth of the image.  See the PNG specification for details.
  312. This call reduces the pixels back down to the true bit depth:
  313.  
  314.     if (info_ptr->valid & PNG_INFO_sBIT)
  315.         png_set_shift(png_ptr, &(info_ptr->sig_bit));
  316.  
  317. PNG files store 3 color pixels in red, green, blue order.  This code
  318. changes the storage of the pixels to blue, green, red:
  319.  
  320.     if (info_ptr->color_type == PNG_COLOR_TYPE_RGB ||
  321.         info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  322.         png_set_bgr(png_ptr);
  323.  
  324. PNG files store RGB pixels packed into 3 bytes. This code expands them
  325. into 4 bytes for windowing systems that need them in this format:
  326.  
  327.    if (info_ptr->bit_depth == 8 &&
  328.       info_ptr->color_type == PNG_COLOR_TYPE_RGB)
  329.       png_set_filler(png_ptr, filler_byte, PNG_FILLER_BEFORE);
  330.  
  331. where filler_byte is the number to fill with, and the location is
  332. either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
  333. you want the filler before the RGB or after.
  334.  
  335. For some uses, you may want a gray-scale image to be represented as
  336. RGB.  This code will do that conversion:
  337.  
  338.    if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY ||
  339.       info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  340.          png_set_gray_to_rgb(png_ptr);
  341.  
  342. The following code handles alpha and transparency by replacing it with
  343. a background value.  If there was a valid bKGD in the file, you can use
  344. it if you want.  However, you can replace it with your own if you want
  345. also.  If there wasn't one in the file, you must supply a color.  If
  346. libpng is doing gamma correction, you will need to tell libpng where
  347. the background came from so it can do the appropriate gamma
  348. correction.  If you have a grayscale and you are using png_set_expand()
  349. to change to a higher bit-depth you must indicate if the background gray
  350. needs to be expanded to the new bit-depth.  Similarly, if you are reading
  351. a paletted image, you must indicate if you have supplied the background
  352. index that needs to be expanded to RGB values.  You can always specify
  353. RGB color values directly when setting your background for paletted images.
  354.  
  355.    png_color_16 my_background;
  356.  
  357.    if (info_ptr->valid & PNG_INFO_bKGD)
  358.       png_set_backgrond(png_ptr, &(info_ptr->background),
  359.             PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
  360.    else
  361.       png_set_background(png_ptr, &my_background,
  362.          PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
  363.  
  364. The following code handles gamma transformations of the data.  Pass
  365. both the file gamma and the desired screen gamma.  If the file does
  366. not have a gamma value, you can pass one anyway if you wish.  Note
  367. that file gammas are inverted from screen gammas.  See the discussions
  368. on gamma in the PNG specification for more information.  It is
  369. strongly recommended that viewers support gamma correction.
  370.  
  371.    if (info_ptr->valid & PNG_INFO_gAMA)
  372.       png_set_gamma(png_ptr, screen_gamma, info_ptr->gamma);
  373.    else
  374.       png_set_gamma(png_ptr, screen_gamma, 0.45);
  375.  
  376. If you need to reduce an RGB file to a paletted file, or if a paletted
  377. file has more entries then will fit on your screen, png_set_dither()
  378. will do that.  Note that this is a simple match dither that merely
  379. finds the closest color available.  This should work fairly well with
  380. optimized palettes, and fairly badly with linear color cubes.  If you
  381. pass a palette that is larger then maximum_colors, the file will
  382. reduce the number of colors in the palette so it will fit into
  383. maximum_colors.  If there is a histogram, it will use it to make
  384. more intelligent choices when reducing the palette.  If there is no
  385. histogram, it may not do as good a job.
  386.  
  387.    if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  388.    {
  389.       if (info_ptr->valid & PNG_INFO_PLTE)
  390.       {
  391.          png_set_dither(png_ptr, info_ptr->palette,
  392.             info_ptr->num_palette, max_screen_colors,
  393.             info_ptr->histogram, 1);
  394.       }
  395.       else
  396.       {
  397.          png_color std_color_cube[MAX_SCREEN_COLORS] =
  398.             { ... colors ... };
  399.  
  400.          png_set_dither(png_ptr, std_color_cube, MAX_SCREEN_COLORS,
  401.             MAX_SCREEN_COLORS, NULL,0);
  402.       }
  403.    }
  404.  
  405. PNG files describe monochrome as black being zero and white being one.
  406. The following code will reverse this (make black be one and white be
  407. zero):
  408.  
  409.    if (info_ptr->bit_depth == 1 &&
  410.       info_ptr->color_type == PNG_COLOR_GRAY)
  411.       png_set_invert_mono(png_ptr);
  412.  
  413. PNG files store 16 bit pixels in network byte order (big-endian,
  414. ie. most significant bits first).  This code chages the storage to the
  415. other way (little-endian, ie. least significant bits first, eg. the
  416. way PCs store them):
  417.  
  418.     if (info_ptr->bit_depth == 16)
  419.         png_set_swap(png_ptr);
  420.  
  421. The last thing to handle is interlacing; this is covered in detail below,
  422. but you must call the function here.
  423.  
  424.    if (info_ptr->interlace_type)
  425.       number_passes = png_set_interlace_handling(png_ptr);
  426.  
  427. After setting the transformations, libpng can update your png_info
  428. structure to reflect any transformations you've requested with this
  429. call.  This is most useful to update the info structures rowbytes
  430. field, so you can use it to allocate your image memory.  This function
  431. will also update your palette with the correct display gamma and
  432. background if these have been given with the calls above.
  433.  
  434.     png_read_update_info(png_ptr, info_ptr);
  435.  
  436. After you call png_read_update_info(), you can allocate any
  437. memory you need to hold the image.  The row data is simply
  438. raw byte data for all forms of images.  As the actual allocation
  439. varies among applications, no example will be given.  If you
  440. are allocating one large chunk, you will need to build an
  441. array of pointers to each row, as it will be needed for some
  442. of the functions below.
  443.  
  444. After you've allocated memory, you can read the image data.
  445. The simplest way to do this is in one function call.  If you are
  446. allocating enough memory to hold the whole image, you can just
  447. call png_read_image() and libpng will read in all the image data
  448. and put it in the memory area supplied.  You will need to pass in
  449. an array of pointers to each row.
  450.  
  451. This function automatically handles interlacing, so you don't need
  452. to call png_set_interlace_handling() or call this function multiple
  453. times, or any of that other stuff necessary with png_read_rows().
  454.  
  455.    png_read_image(png_ptr, row_pointers);
  456.  
  457. where row_pointers is:
  458.  
  459.    png_bytep row_pointers[height];
  460.  
  461. You can point to void or char or whatever you use for pixels.
  462.  
  463. If you don't want to read int the whole image at once, you can
  464. use png_read_rows() instead.  If there is no interlacing (check
  465. info_ptr->interlace_type), this is simple:
  466.  
  467.     png_read_rows(png_ptr, row_pointers, NULL, number_of_rows);
  468.  
  469. where row_pointers is the same as in the png_read_image() call.
  470.  
  471. If you are doing this just one row at a time, you can do this with
  472. row_pointers:
  473.  
  474.     png_bytep row_pointers = row;
  475.     png_read_row(png_ptr, &row_pointers, NULL);
  476.  
  477. If the file is interlaced (info_ptr->interlace_type != 0), things get
  478. somewhat harder.  The only currently (as of 6/96 -- PNG
  479. Specification version 1.0) defined interlacing scheme for PNG files
  480. (info_ptr->interlace_type == 1) is a someewhat complicated 2D interlace
  481. scheme, known as Adam7, that breaks down an image into seven smaller
  482. images of varying size, based on an 8x8 grid.
  483.  
  484. libpng can fill out those images or it can give them to you "as is".
  485. If you want them filled out, there are two ways to do that.  The one
  486. mentioned in the PNG specification is to expand each pixel to cover
  487. those pixels that have not been read yet.  This results in a blocky
  488. image for the first pass, which gradually smoothes out as more pixels
  489. are read.  The other method is the "sparkle" method, where pixels are
  490. draw only in their final locations, with the rest of the image remaining
  491. whatever colors they were initialized to before the start of the read.
  492. The first method usually looks better, but tends to be slower, as there
  493. are more pixels to put in the rows.
  494.  
  495. If you don't want libpng to handle the interlacing details, just call
  496. png_read_rows() seven times to read in all seven images.  Each of the
  497. images are valid images by themselves, or they can be combined on an
  498. 8x8 grid to form a single image (although if you intend to combine them
  499. you would be far better off using the libpng interlace handling).
  500.  
  501. The first pass will return an image 1/8 as wide as the entire image
  502. (every 8th column starting in column 0) and 1/8 as high as the original
  503. (every 8th row starting in row 0), the second will be 1/8 as wide
  504. (starting in column 4) and 1/8 as high (also starting in row 0).  The
  505. third pass will be 1/4 as wide (every 4th pixel starting in row 0) and
  506. 1/8 as high (every 8th row starting in row 4), and the fourth pass will
  507. be 1/4 as wide and 1/4 as high (every 4th column starting in column 2,
  508. and every 4th row starting in row 0).  The fifth pass will return an
  509. image 1/2 as wide, and 1/4 as high (starting at column 0 and row 2),
  510. while the sixth pass will be 1/2 as wide and 1/2 as high as the original
  511. (starting in column 1 and row 0).  The seventh and final pass will be as
  512. wide as the original, and 1/2 as high, containing all of the odd
  513. numbered scanlines.  Phew!
  514.  
  515. If you want libpng to expand the images, call this before calling
  516. png_start_read_image() or png_read_update_info():
  517.  
  518.     if (info_ptr->interlace_type)
  519.         number_passes = png_set_interlace_handling(png_ptr);
  520.  
  521. This will return the number of passes needed.  Currently, this
  522. is seven, but may change if another interlace type is added.
  523. This function can be called even if the file is not interlaced,
  524. where it will return one pass.
  525.  
  526. If you are not going to display the image after each pass, but are
  527. going to wait until the entire image is read in, use the sparkle
  528. effect.  This effect is faster and the end result of either method
  529. is exactly the same.  If you are planning on displaying the image
  530. after each pass, the rectangle effect is generally considered the
  531. better looking one.
  532.  
  533. If you only want the "sparkle" effect, just call png_read_rows() as
  534. normal, with the third parameter NULL.  Make sure you make pass over
  535. the image number_passes times, and you don't change the data in the
  536. rows between calls.  You can change the locations of the data, just
  537. not the data.  Each pass only writes the pixels appropriate for that
  538. pass, and assumes the data from previous passes is still valid.
  539.  
  540.     png_read_rows(png_ptr, row_pointers, NULL, number_of_rows);
  541.  
  542. If you only want the first effect (the rectangles), do the same as
  543. before except pass the row buffer in the third parameter, and leave
  544. the second parameter NULL.
  545.  
  546.     png_read_rows(png_ptr, NULL, row_pointers, number_of_rows);
  547.  
  548. After you are finished reading the image, you can finish reading
  549. the file.  If you are interested in comments or time, which may be
  550. stored either before or after the image data, you should pass the
  551. info_ptr pointer from the png_read_info() call, or you can pass a
  552. separate png_info struct if you want to keep the comments from
  553. before and after the image separate.  If you are not interested, you
  554. can pass NULL.
  555.  
  556.    png_read_end(png_ptr, end_info);
  557.  
  558. When you are done, you can free all memory allocated by libpng like this:
  559.  
  560.    png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  561.  
  562. For a more compact example of reading a PNG image, see the file example.c.
  563.  
  564.  
  565. Reading PNG files progressively:
  566.  
  567. The progressive reader is slightly different then the non-progressive
  568. reader.  Instead of calling png_read_info(), png_read_rows(), and
  569. png_read_end(), you make one call to png_process_data(), which calls
  570. callbacks when it has the info, a row, or the end of the image.  You
  571. set up these callbacks with png_set_progressive_read_fn().  You don't
  572. have to worry about the input/output functions of libpng, as you are
  573. giving the library the data directly in png_process_data().  I will
  574. assume that you have read the section on reading PNG files above,
  575. so I will only highlight the differences (although I will show
  576. all of the code).
  577.  
  578. png_structp png_ptr;
  579. png_infop info_ptr;
  580.  
  581. /*  An example code fragment of how you would initialize the progressive
  582.     reader in your application. */
  583. int
  584. initialize_png_reader()
  585. {
  586.     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  587.         (void *)user_error_ptr, user_error_fn, user_warning_fn);
  588.     if (!png_ptr)
  589.         return -1;
  590.     info_ptr = png_create_info_struct(png_ptr);
  591.     if (!info_ptr)
  592.     {
  593.         png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  594.         return -1;
  595.     }
  596.  
  597.     if (setjmp(png_ptr->jmpbuf))
  598.     {
  599.         png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  600.         return -1;
  601.     }
  602.  
  603.     /* This one's new.  You can provide functions to be called
  604.        when the header info is valid, when each row is completed,
  605.        and when the image is finished.  If you aren't using all
  606.        functions, you can specify a NULL parameter.  You can use
  607.        any struct as the user_ptr (cast to a void pointer for the
  608.        function call), and retrieve the pointer from inside the
  609.        callbacks using the function png_get_progressive_ptr(png_ptr);        
  610.        which will return a void pointer, which you have to cast
  611.        appropriately.
  612.      */
  613.     png_set_progressive_read_fn(png_ptr, (void *)user_ptr,
  614.         info_callback, row_callback, end_callback);
  615.  
  616.     return 0;
  617. }
  618.  
  619. /* A code fragment that you call as you recieve blocks of data */
  620. int
  621. process_data(png_bytep buffer, png_uint_32 length)
  622. {
  623.     if (setjmp(png_ptr->jmpbuf))
  624.     {
  625.         png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
  626.         return -1;
  627.     }
  628.  
  629.     /* This one's new also.  Simply give it a chunk of data
  630.        from the file stream (in order, of course).  On machines
  631.        with segmented memory models machines, don't give it any 
  632.        more than 64K.  The library seems to run fine with sizes 
  633.        of 4K. Although you can give it much less if necessary 
  634.        (I assume you can give it chunks of 1 byte, I haven't
  635.        tried less then 256 bytes yet).  When this function returns,
  636.        you may want to display any rows that were generated in the
  637.        row callback if you don't already do so there. 
  638.      */
  639.     png_process_data(png_ptr, info_ptr, buffer, length);
  640.     return 0;
  641. }
  642.  
  643. /* This function is called (as set by png_set_progressive_fn() above)
  644.    when enough data has been supplied so all of the header has been read.
  645.  */
  646. void
  647. info_callback(png_structp png_ptr, png_infop info)
  648. {
  649.     /* Do any setup here, including setting any of the transformations
  650.        mentioned in the Reading PNG files section.  For now, you _must_
  651.        call either png_start_read_image() or png_read_update_info()
  652.        after all the transformations are set (even if you don't set
  653.        any).  You may start getting rows before png_process_data()
  654.        returns, so this is your last chance to prepare for that.
  655.      */
  656. }
  657.  
  658. /* This function is called when each row of image data is complete */
  659. void
  660. row_callback(png_structp png_ptr, png_bytep new_row,
  661.     png_uint_32 row_num, int pass)
  662. {
  663.     /* If the image is interlaced, and you turned on the interlace
  664.        handler, this function will be called for every row in every pass.
  665.        Some of these rows will not be changed from the previous pass.
  666.        When the row is not changed, the new_row variable will be NULL.
  667.        The rows and passes are called in order, so you don't really
  668.        need the row_num and pass, but I'm supplying them because it
  669.        may make your life easier.
  670.  
  671.        For the non-NULL rows of interlaced images, you must call
  672.        png_progressive_combine_row() passing in the row and the
  673.        old row.  You can call this function for NULL rows (it will
  674.        just return) and for non-interlaced images (it just does the
  675.        memcpy for you) if it will make the code easier.  Thus, you
  676.        can just do this for all cases:
  677.      */
  678.  
  679.         png_progressive_combine_row(png_ptr, old_row, new_row);
  680.  
  681.     /* where old_row is what was displayed for previous rows.  Note
  682.        that the first pass (pass == 0, really) will completely cover
  683.        the old row, so the rows do not have to be initialized.  After
  684.        the first pass (and only for interlaced images), you will have
  685.        to pass the current row, and the function will combine the
  686.        old row and the new row.
  687.     */  
  688. }
  689.  
  690. void
  691. end_callback(png_structp png_ptr, png_infop info)
  692. {
  693.     /* This function is called after the whole image has been read,
  694.        including any chunks after the image (up to and including
  695.        the IEND).  You will usually have the same info chunk as you
  696.        had in the header, although some data may have been added
  697.        to the comments and time fields.
  698.  
  699.        Most people won't do much here, perhaps setting a flag that
  700.        marks the image as finished.
  701.      */
  702. }
  703.  
  704.  
  705.  
  706. IV. Writing
  707.  
  708. Much of this is very similar to reading.  However, everything of
  709. importance is repeated here, so you won't have to constantly look
  710. back up in the reading section to understand writing.
  711.  
  712. You will want to do the I/O initialization before you get into libpng,
  713. so if it doesn't work, you don't have anything to undo. If you are not
  714. using the standard I/O functions, you will need to replace them with
  715. custom writing functions.  See the discussion under Customizing libpng.
  716.     
  717.     FILE *fp = fopen(file_name, "wb");
  718.     if (!fp)
  719.     {
  720.        return;
  721.     }
  722.  
  723. Next, png_struct and png_info need to be allocated and initialized.
  724. As these can be both relatively large, you may not want to store these
  725. on the stack, unless you have stack space to spare.  Of course, you
  726. will want to check if they return NULL.
  727.  
  728.     png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  729.        (void *)user_error_ptr, user_error_fn, user_warning_fn);
  730.     if (!png_ptr)
  731.        return;
  732.  
  733.     png_infop info_ptr = png_create_info_struct(png_ptr);
  734.     if (!info_ptr)
  735.     {
  736.        png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  737.        return;
  738.     }
  739.  
  740. After you have these structures, you will need to set up the
  741. error handling.  When libpng encounters an error, it expects to
  742. longjmp() back to your routine.  Therefore, you will need to call
  743. setjmp and pass the jmpbuf field of your png_struct.  If you
  744. write the file from different routines, you will need to update
  745. the jmpbuf field every time you enter a new routine that will
  746. call a png_ function.  See your documentation of setjmp/longjmp
  747. for your compiler for more information on setjmp/longjmp.  See
  748. the discussion on libpng error handling in the Customizing Libpng
  749. section below for more information on the libpng error handling.
  750.     
  751.     if (setjmp(png_ptr->jmpbuf))
  752.     {    
  753.         png_destroy_write_struct(&png_ptr, &info_ptr);
  754.         fclose(fp);
  755.         return;
  756.     }
  757.  
  758. Now you need to set up the input code.  The default for libpng is to
  759. use the C function fwrite().  If you use this, you will need to pass a
  760. valid FILE * in the function png_init_io().  Be sure that the file is
  761. opened in binary mode.  Again, if you wish to handle writing data in
  762. another way, see the discussion on libpng I/O handling in the Customizing
  763. Libpng section below.
  764.  
  765.     png_init_io(png_ptr, fp);
  766.  
  767. You now have the option of modifying how the compression library will
  768. run.  The following functions are mainly for testing, but may be useful
  769. in some cases, like if you need to write PNG files extremely fast and
  770. are willing to give up some compression, or if you want to get the
  771. maximum possible compression at the expense of slower writing.  If you
  772. have no special needs in this area, let the library do what it wants by
  773. not calling this function at all, as it has been tuned to deliver a good
  774. speed/compression ratio. The second parameter to png_set_filter() is
  775. the filter method, for which the only valid value is '0' (as of the
  776. 06/96 PNG specification.  The third parameter is a flag that indicates
  777. which filter type(s) are to be tested for each scanline.  See the
  778. Compression Library for details on the specific filter types.
  779.  
  780.     
  781.     /* turn on or off filtering, and/or choose specific filters */
  782.     png_set_filter(png_ptr, 0,
  783.        PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_PAETH);
  784.  
  785. The png_set_compression_???() functions interface to the zlib compression
  786. library, and should mostly be ignored unless you really know what you are
  787. doing.  The only generally useful call is png_set_compression_level()
  788. which changes how much time zlib spends on trying to compress the image
  789. data.  See the Compression Library for details on the compression levels.
  790.  
  791.     /* set the zlib compression level */
  792.     png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
  793.  
  794.     /* set other zlib parameters */
  795.     png_set_compression_mem_level(png_ptr, 8);
  796.     png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
  797.     png_set_compression_window_bits(png_ptr, 15);
  798.     png_set_compression_method(png_ptr, 8);
  799.  
  800. You now need to fill in the png_info structure with all the data you
  801. wish to write before the actual image.  Note that the only thing you
  802. are allowed to write after the image is the text chunks and the time
  803. chunk (as of PNG Specification 1.0, anyway).  See png_write_end() and
  804. the latest PNG specification for more information on that.  If you
  805. wish to write them before the image, fill them in now, and flag that
  806. data as being valid.  If you want to wait until after the data, don't
  807. fill them until png_write_end().  For all the fields in png_info and
  808. their data types, see png.h.  For explanations of what the fields
  809. contain, see the PNG specification.
  810.  
  811. Some of the more important parts of the png_info are:
  812.  
  813.     width          - holds the width of the file
  814.     height         - holds the height of the file
  815.     bit_depth      - holds the bit depth of one of the image channels
  816.     color_type     - describes the channels and what they mean
  817.                      see the PNG_COLOR_TYPE_ defines for more information
  818.     interlace_type - allowed values are 0 for none, 1 for interlaced
  819.     valid          - this describes which optional chunks to write to the
  820.                      file.  Note that if you are writing a
  821.                      PNG_COLOR_TYPE_PALETTE file, the PLTE chunk is not
  822.                      optional, but must still be marked for writing.  To
  823.                      mark chunks for writing, logical OR '|' valid with
  824.                      the appropriate PNG_INFO_<chunk name> define.
  825.     palette        - the palette for the file (PNG_INFO_PLTE)
  826.     num_palette    - number of entries in the palette
  827.     gamma          - the gamma the file is written at (PNG_INFO_gAMA)
  828.     sig_bit        - the number of significant bits (PNG_INFO_sBIT)
  829.                      for the gray, red, green, and blue channels, whichever
  830.                      are appropriate for the given color type.
  831.     trans_values   - transparent pixel for non-paletted images (PNG_INFO_tRNS)
  832.     trans          - array of transparent entries for paletted images
  833.     num_trans      - number of transparent entries
  834.     hist           - histogram of palette (PNG_INFO_hIST)
  835.     mod_time       - time image was last modified (PNG_VALID_tIME)
  836.     background     - background color (PNG_VALID_bKGD)
  837.     text           - text comments in the file.
  838.     num_text       - number of comments
  839.  
  840. A quick word about text and num_text.  text is an array of png_text
  841. structures.  num_text is the number of valid structures in the array.
  842. If you want, you can use max_text to hold the size of the array, but
  843. libpng ignores it for writing (it does use it for reading).  Each
  844. png_text structure holds a keyword-text value, and a compression type.
  845. The compression types have the same valid numbers as the compression
  846. types of the image data.  Currently, the only valid number is zero.
  847. However, you can store text either compressed or uncompressed, unlike
  848. images which always have to be compressed.  So if you don't want the
  849. text compressed, set the compression type to -1.  Until text gets
  850. around 1000 bytes, it is not worth compressing it.
  851.  
  852. The keywords that are given in the PNG Specification are:
  853.  
  854.             Title            Short (one line) title or caption for image
  855.             Author           Name of image's creator
  856.             Description      Description of image (possibly long)
  857.             Copyright        Copyright notice
  858.             Creation Time    Time of original image creation
  859.             Software         Software used to create the image
  860.             Disclaimer       Legal disclaimer
  861.             Warning          Warning of nature of content
  862.             Source           Device used to create the image
  863.             Comment          Miscellaneous comment; conversion from other
  864.                              image format
  865.  
  866. The keyword-text pairs work like this.  Keywords should be short
  867. simple descriptions of what the comment is about.  Some typical
  868. keywords are found in the PNG specification, as is some recomendations
  869. on keywords.  You can repeat keywords in a file.  You can even write
  870. some text before the image and some after.  For example, you may want
  871. to put a description of the image before the image, but leave the
  872. disclaimer until after, so viewers working over modem connections
  873. don't have to wait for the disclaimer to go over the modem before
  874. they start seeing the image.  Finally, keywords should be full
  875. words, not abbreviations.  Keywords and text are in the ISO 8859-1
  876. (Latin-1) character set (a superset of regular ASCII) and can not
  877. contain NUL characters, and should not contain control or other
  878. unprintable characters.  To make the comments widely readable, stick
  879. with basic ASCII, and avoid machine specific character set extensions
  880. like the IBM-PC character set.  The keyword must be present, but
  881. you can leave off the text string on non-compressed pairs.
  882. Compressed pairs must have a text string, as only the text string
  883. is compressed anyway, so the compression would be meaningless.
  884.  
  885. PNG supports modification time via the png_time structure.  Two
  886. conversion routines are proved, png_convert_from_time_t() for
  887. time_t and png_convert_from_struct_tm() for struct tm.  The
  888. time_t routine uses gmtime().  You don't have to use either of
  889. these, but if you wish to fill in the png_time structure directly,
  890. you should provide the time in universal time (GMT) if possible
  891. instead of your local time.  Note that the year number is the full
  892. year (ie 1996, rather than 96), and that months start with 1.
  893.  
  894. You are now ready to write all the file information up to the actual
  895. image data.  You do this with a call to png_write_info().
  896.  
  897.     png_write_info(png_ptr, info_ptr);
  898.  
  899. After you've written the file information, you can set up the library
  900. to handle any special transformations of the image data.  The various
  901. ways to transform the data will be described in the order that they
  902. should occur.  This is important, as some of these change the color
  903. type and/or bit depth of the data, and some others only work on
  904. certain color types and bit depths.  Even though each transformation
  905. checks to see if it has data that it can do somthing with, you should
  906. make sure to only enable a transformation if it will be valid for the
  907. data.  For example, don't swap red and blue on grayscale data.
  908.  
  909. PNG files store RGB pixels packed into 3 bytes.  This code tells
  910. the library to expect input data with 4 bytes per pixel
  911.  
  912.     png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  913.  
  914. where the 0 is the value that will be put in the 4th byte, and the
  915. location is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending
  916. upon whether the filler byte is stored XRGB or RGBX.
  917.  
  918. PNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as
  919. they can, resulting in, for example, 8 pixels per byte for 1 bit files.
  920. If the data is supplied at 1 pixel per byte, use this code, which will
  921. correctly pack the pixels into a single byte:
  922.  
  923.     png_set_packing(png_ptr);
  924.  
  925. PNG files reduce possible bit depths to 1, 2, 4, 8, and 16.  If your
  926. data is of another bit depth, you can write an sBIT chunk into the
  927. file so that decoders can get the original data if desired.
  928.     
  929.     /* Do this before png_write_info() */
  930.     info_ptr->valid |= PNG_INFO_sBIT;
  931.  
  932.     /* Set the true bit depth of the image data */
  933.     if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  934.     {
  935.         info_ptr->sig_bit.red = true_bit_depth;
  936.         info_ptr->sig_bit.green = true_bit_depth;
  937.         info_ptr->sig_bit.blue = true_bit_depth;
  938.     }
  939.     else
  940.     {
  941.         info_ptr->sig_bit.gray = true_bit_depth;
  942.     }
  943.  
  944.     if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  945.     {
  946.         info_ptr->sig_bit.alpha = true_bit_depth;
  947.     }
  948.  
  949. If the data is stored in the row buffer in a bit depth other than
  950. one supported by PNG (ie 3 bit data in the range 0-7 for a 4-bit PNG),
  951. this will scale the values to appear to be the correct bit depth as
  952. is required by PNG.
  953.  
  954.     png_set_shift(png_ptr, &(info_ptr->sig_bit));
  955.  
  956. PNG files store 16 bit pixels in network byte order (big-endian,
  957. ie. most significant bits first).  This code would be used if they are
  958. supplied the other way (little-endian, ie. least significant bits
  959. first, eg. the way PCs store them):
  960.  
  961.     png_set_swap(png_ptr);
  962.  
  963. PNG files store 3 color pixels in red, green, blue order.  This code
  964. would be used if they are supplied as blue, green, red:
  965.  
  966.     png_set_bgr(png_ptr);
  967.  
  968. PNG files describe monochrome as black being zero and white being
  969. one. This code would be used if the pixels are supplied with this reversed
  970. (black being one and white being zero):
  971.  
  972.     png_set_invert(png_ptr);
  973.  
  974. It is possible to have libpng flush any pending output, either manually,
  975. or automatically after a certain number of lines have been written.  To
  976. flush the output stream a single time call:
  977.  
  978.     png_write_flush(png_ptr);
  979.  
  980. and to have libpng flush the output stream periodically after a certain
  981. number of scanlines have been written, call:
  982.  
  983.     png_set_flush(png_ptr, nrows);
  984.  
  985. Note that the distance between rows is from the last time png_write_flush()
  986. was called, or the first row of the image if it has never been called.
  987. So if you write 50 lines, and then png_set_flush 25, it will flush the
  988. output on the next scanline, and every 25 lines thereafter, unless
  989. png_write_flush()ls is called before 25 more lines have been written.
  990. If nrows is too small (less than about 10 lines for a 640 pixel wide
  991. RGB image) the image compression may decrease noticably (although this
  992. may be acceptable for real-time applications).  Infrequent flushing will
  993. only degrade the compression performance by a few percent over images
  994. that do not use flushing.
  995.  
  996. That's it for the transformations.  Now you can write the image data.
  997. The simplest way to do this is in one function call.  If have the
  998. whole image in memory, you can just call png_write_image() and libpng
  999. will write the image.  You will need to pass in an array of pointers to
  1000. each row.  This function automatically handles interlacing, so you don't
  1001. need to call png_set_interlace_handling() or call this function multiple
  1002. times, or any of that other stuff necessary with png_write_rows().
  1003.  
  1004.     png_write_image(png_ptr, row_pointers);
  1005.  
  1006. where row_pointers is:
  1007.  
  1008.     png_bytef *row_pointers[height];
  1009.  
  1010. You can point to void or char or whatever you use for pixels.
  1011.  
  1012. If you can't want to write the whole image at once, you can
  1013. use png_write_rows() instead.  If the file is not interlaced,
  1014. this is simple:
  1015.  
  1016.     png_write_rows(png_ptr, row_pointers, number_of_rows);
  1017.  
  1018. row_pointers is the same as in the png_write_image() call.
  1019.  
  1020. If you are just writing one row at a time, you can do this with
  1021. row_pointers:
  1022.  
  1023.     png_bytep row_pointer = row;
  1024.  
  1025.     png_write_row(png_ptr, &row_pointer);
  1026.  
  1027. When the file is interlaced, things can get a good deal more
  1028. complicated.  The only currently (as of 6/96 -- PNG Specification
  1029. version 1.0) defined interlacing scheme for PNG files is a
  1030. compilcated interlace scheme, known as Adam7, that breaks down an
  1031. image into seven smaller images of varying size.  libpng will build
  1032. these images for you, or you can do them yourself.  If you want to
  1033. build them yourself, see the PNG specification for details of which
  1034. pixels to write when.
  1035.  
  1036. If you don't want libpng to handle the interlacing details, just
  1037. use png_set_interlace_handling() and call png_write_rows() the
  1038. correct number of times to write all seven sub-images.
  1039.  
  1040. If you want libpng to build the sub-images, call this before you start
  1041. writing any rows:
  1042.  
  1043.     number_passes = png_set_interlace_handling(png_ptr);
  1044.  
  1045. This will return the number of passes needed.  Currently, this
  1046. is seven, but may change if another interlace type is added.
  1047.  
  1048. Then write the complete image number_passes times.
  1049.  
  1050.     png_write_rows(png_ptr, row_pointers, number_of_rows);
  1051.  
  1052. As some of these rows are not used, and thus return immediately,
  1053. you may want to read about interlacing in the PNG specification,
  1054. and only update the rows that are actually used.
  1055.  
  1056. After you are finished writing the image, you should finish writing
  1057. the file.  If you are interested in writing comments or time, you should
  1058. pass the an appropriately filled png_info pointer.  If you
  1059. are not interested, you can pass NULL.  If you have written text at
  1060. the beginning and are not writing more at the end, you should set
  1061. info_ptr->num_text = 0, or the text will be written again here.
  1062.  
  1063.     png_write_end(png_ptr, info_ptr);
  1064.  
  1065. When you are done, you can free all memory used by libpng like this:
  1066.  
  1067.     png_destroy_write_struct(&png_ptr, &info_ptr);
  1068.  
  1069. You must free any data you allocated for info_ptr, such as comments,
  1070. palette, or histogram, before the call to png_destroy_write_struct();
  1071.  
  1072. For a more compact example of writing a PNG image, see the file example.c.
  1073.  
  1074.  
  1075. V. Modifying/Customizing libpng:
  1076.  
  1077. There are two issues here.  The first is changing how libpng does
  1078. standard things like memory allocation, input/output, and error handling.
  1079. The second deals with more complicated things like adding new chunks,
  1080. adding new transformations, and generally changing how libpng works.
  1081.  
  1082. All of the memory allocation, input/output, and error handling in
  1083. libpng goes through callbacks which are user setable.  The default
  1084. routines are in pngmem.c, pngrio.c, pngwio.c, and pngerror.c respectively.
  1085. To change these functions, call the approprate png_set_???_fn() function.
  1086.  
  1087. Memory allocation is done through the functions png_large_malloc(),
  1088. png_malloc(), png_realloc(), png_large_free(), and png_free().  These
  1089. currently just call the standard C functions.  The large functions must
  1090. handle exactly 64K, but they don't have to handle more than that.  If
  1091. your pointers can't access more then 64K at a time, you will want to
  1092. set MAXSEG_64K in zlib.h.  Since it is unlikely that the method of
  1093. handling memory allocation on a platform will change between applications,
  1094. these functions must be modified in the library at compile time.
  1095.  
  1096. Input/Output in libpng is done throught png_read() and png_write(), which
  1097. currently just call fread() and fwrite().  The FILE * is stored in
  1098. png_struct, and is initialized via png_init_io().  If you wish to change
  1099. the method of I/O, the library supplies callbacks that you can set through
  1100. the function png_set_read_fn() and png_set_write_fn() at run time.  These
  1101. functions also provide a void pointer that can be retrieved via the function
  1102. png_get_io_ptr().  For example:
  1103.  
  1104.     png_set_read_fn(png_structp png_ptr, voidp io_ptr,
  1105.         png_rw_ptr read_data_fn)
  1106.  
  1107.     png_set_write_fn(png_structp png_ptr, voidp io_ptr,
  1108.         png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn);
  1109.  
  1110.     voidp io_ptr = png_get_io_ptr(png_ptr);
  1111.  
  1112. The replacement I/O functions should have prototypes as follows:
  1113.  
  1114.     void user_read_data(png_structp png_ptr, png_bytep data,
  1115.         png_uint_32 length);
  1116.     void user_write_data(png_structp png_ptr, png_bytep data,
  1117.         png_uint_32 length);
  1118.     void user_flush_data(png_structp png_ptr);
  1119.  
  1120. Supplying NULL for the read, write, or flush functions sets them back
  1121. to using the default C stream functions.  It is an error to read from
  1122. a write stream, and vice versa.
  1123.  
  1124. Error handling in libpng is done through png_error() and png_warning().
  1125. Errors handled through png_error() are fatal, meaning that png_error()
  1126. should never return to it's caller.  Currently, this is handled via
  1127. setjmp() and longjmp(), but you could change this to do things like
  1128. exit() if you should wish.  On non-fatal errors, png_warning() is called
  1129. to print a warning message, and then control returns to the calling code.
  1130. By default png_error() and png_warning() print a message on stderr via
  1131. fprintf() unless the library is compiled with PNG_NO_STDIO defined.  If
  1132. you wish to change the behavior of the error functions, you will need to
  1133. set up your own message callbacks.  These functions are normally supplied
  1134. at the time that the png_struct is created.  It is also possible to change
  1135. these functions after png_create_???_struct() has been called by calling:
  1136.  
  1137.     png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  1138.         png_error_ptr error_fn, png_error_ptr warning_fn);
  1139.  
  1140.     png_voidp error_ptr = png_get_error_ptr(png_ptr);
  1141.  
  1142. If NULL is supplied for either error_fn or warning_fn, then the libpng
  1143. default function will be used, calling fprintf() and/or longjmp() if a
  1144. problem is encountered.  The replacement error functions should have
  1145. parameters as follows:
  1146.  
  1147.     void user_error_fn(png_struct png_ptr, png_const_charp error_msg);
  1148.     void user_warning_fn(png_struct png_ptr, png_const_charp warning_msg);
  1149.  
  1150. The motivation behind using setjmp() and longjmp() is the C++ throw and
  1151. catch exception handling methods.  This makes the code much easier to write,
  1152. as there is no need to check every return code of every function call.
  1153. However, there are some uncertainties about the status of local variables
  1154. after a longjmp, so the user may want to be careful about doing anything after
  1155. setjmp returns non zero besides returning itself.  Consult your compiler
  1156. documentation for more details.
  1157.  
  1158. If you need to read or write custom chunks, you will need to get deeper
  1159. into the libpng code, as a mechanism has not yet been supplied for user
  1160. callbacks with custom chunks.  First, read the PNG specification, and have
  1161. a first level of understanding of how it works.  Pay particular attention
  1162. to the sections that describe chunk names, and look at how other chunks
  1163. were designed, so you can do things similarly.  Second, check out the
  1164. sections of libpng that read and write chunks.  Try to find a chunk that
  1165. is similar to yours and copy off of it.  More details can be found in the
  1166. comments inside the code.  A way of handling unknown chunks in a generic
  1167. method, potentially via callback functions, would be best.
  1168.  
  1169. If you wish to write your own transformation for the data, look through
  1170. the part of the code that does the transformations, and check out some of
  1171. the simpler ones to get an idea of how they work.  Try to find a similar
  1172. transformation to the one you want to add and copy off of it.  More details
  1173. can be found in the comments inside the code itself.
  1174.  
  1175. Configuring for 16 bit platforms:
  1176.  
  1177. You may need to change the png_large_malloc() and png_large_free()
  1178. routines in pngmem.c, as these are requred to allocate 64K, although
  1179. there is already support for many of the common DOS compilers.  Also,
  1180. you will want to look into zconf.h to tell zlib (and thus libpng) that
  1181. it cannot allocate more then 64K at a time.  Even if you can, the memory
  1182. won't be accessable.  So limit zlib and libpng to 64K by defining MAXSEG_64K.
  1183.  
  1184. Configuring for DOS:
  1185.  
  1186. For DOS users which only have access to the lower 640K, you will
  1187. have to limit zlib's memory usage via a png_set_compression_mem_level()
  1188. call.  See zlib.h or zconf.h in the zlib library for more information.
  1189.  
  1190. Configuring for Medium Model:
  1191.  
  1192. Libpng's support for medium model has been tested on most of the popular
  1193. complers.  Make sure MAXSEG_64K gets defined, USE_FAR_KEYWORD gets
  1194. defined, and FAR gets defined to far in pngconf.h, and you should be
  1195. all set.  Everything in the library (except for zlib's structure) is
  1196. expecting far data.  You must use the typedefs with the p or pp on
  1197. the end for pointers (or at least look at them and be careful).  Make
  1198. note that the row's of data are defined as png_bytepp which is a
  1199. unsigned char far * far *.
  1200.  
  1201. Configuring for gui/windowing platforms:
  1202.  
  1203. You will need to write new error and warning functions that use the GUI
  1204. interface, as described previously, and set them to be the error and
  1205. warning functions at the time that png_create_???_struct() is called,
  1206. in order to have them available during the structure initialization.
  1207. They can be changed later via png_set_error_fn().  On some compliers,
  1208. you may also have to change the memory allocators (png_malloc, etc.).
  1209.  
  1210. Configuring for compiler xxx:
  1211.  
  1212. All includes for libpng are in pngconf.h.  If you need to add/change/delete
  1213. an include, this is the place to do it.  The includes that are not
  1214. needed outside libpng are protected by the PNG_INTERNAL definition,
  1215. which is only defined for those routines inside libpng itself.  The
  1216. files in libpng proper only include png.h, which includes pngconf.h.
  1217.  
  1218. Configuring zlib:
  1219.  
  1220. There are special functions to configure the compression.  Perhaps the
  1221. most useful one changes the compression level, which currently uses
  1222. input compression values in the range 0 - 9.  The library normally
  1223. uses the default compression level (Z_DEFAULT_COMPRESSION = 6), but if
  1224. speed is not critical it is possible to configure it for maximum
  1225. compression (Z_BEST_COMPRESSION = 9) to generate smaller PNG files.
  1226. For online applications it may be desirable to have maximum speed
  1227. (Z_BEST_SPEED = 1).  With versions of zlib after v0.99, you can also
  1228. specify no compression (Z_NO_COMPRESSION = 0), but this would create
  1229. files larger than just storing the raw bitmap.  You can specify the
  1230. compression level by calling:
  1231.  
  1232.     png_set_compression_mem_level(png_ptr, level);
  1233.  
  1234. Another useful one is to reduce the memory level used by the library.
  1235. The memory level defaults to 8, but it can be lowered if you are
  1236. short on memory (running DOS, for example, where you only have 640K).
  1237.  
  1238.     png_set_compression_mem_level(png_ptr, level);
  1239.  
  1240. If you want to control whether libpng uses filtering or not, you
  1241. can call this function.  Filtering is enabled by default for RGB
  1242. and grayscale images (with and without alpha), and for 8-bit
  1243. paletted images, but not for paletted images with bit depths less
  1244. than 8 bits/pixel.  The 'method' parameter sets the main filtering
  1245. method, which is currently only '0' in the PNG 1.0 specification.
  1246. The 'filters' parameter sets which filter(s), if any, should be
  1247. used for each scanline.  Possible values are PNG_ALL_FILTERS and
  1248. PNG_NO_FILTERS to turn filtering on and off, respectively.
  1249. Individual filter types are PNG_FILTER_NONE, PNG_FILTER_SUB,
  1250. PNG_FILTER_UP, PNG_FILTER_AVG, PNG_FILTER_PAETH, which can be bitwise
  1251. ORed together '|' to specify one or more filters to use.  These
  1252. filters are described in more detail in the PNG specification.  If
  1253. you intend to change the filter type during the course of writing
  1254. the image, you should start with flags set for all of the filters
  1255. you intend to use so that libpng can initialize its internal
  1256. structures appropriately for all of the filter types.
  1257.  
  1258.     png_set_filter(png_ptr, method, filters);
  1259.  
  1260. The other functions are for configuring zlib.  They are not recommended
  1261. for normal use and may result in writing an invalid PNG file.  See
  1262. zlib.h for more information on what these mean.
  1263.  
  1264.     png_set_compression_strategy(png_ptr, strategy);
  1265.     png_set_compression_window_bits(png_ptr, window_bits);
  1266.     png_set_compression_method(png_ptr, method);
  1267.  
  1268. Except for png_set_filter(), all of these are just controlling zlib,
  1269. so see the zlib documentation (zlib.h and zconf.h) for more information.
  1270.  
  1271. Removing unwanted object code:
  1272.  
  1273. There are a bunch of #define's in pngconf.h that control what parts of
  1274. libpng are compiled.  All the defines end in _SUPPORT.  If you are
  1275. never going to use an ability, you can change the #define to #undef
  1276. before recompiling libpng and save yourself code and data space.  All
  1277. the reading and writing specific code are in seperate files, so the
  1278. linker should only grab the files it needs.  However, if you want to
  1279. make sure, or if you are building a stand alone library, all the
  1280. reading files start with pngr and all the writing files start with
  1281. pngw.  The files that don't match either (like png.c, pngtrans.c, etc.)
  1282. are used for both reading and writing, and always need to be included.
  1283. The progressive reader is in pngpread.c
  1284.  
  1285. If you are creating or distributing a dynamically linked library (a .so
  1286. or DLL file), you should not remove or disable any parts of the
  1287. library, as this will cause applications linked with different versions
  1288. of the library to fail if they call functions not available in your
  1289. library.  The size of the library itself should not be an issue, because
  1290. only those sections which are actually used will be loaded into memory.
  1291.  
  1292. Changes to Libpng from version 0.88 to version 0.89
  1293.  
  1294. It should be noted that version 0.89 of libpng is not distributed by
  1295. the original author, Guy Schalnat, but rather Andreas Dilger, although
  1296. all of the copyright messages have been left in Guy's name.
  1297.  
  1298. The old libpng functions png_read_init(), png_write_init() and
  1299. png_info_init() still exist in the 0.89 version of the library, as
  1300. do png_read_destroy() and png_write_destroy().  The preferred method
  1301. of creating and initializing the libpng structures is via the
  1302. png_create_read_struct(), png_create_write_struct(), and
  1303. png_create_info_struct() because they isolate the size of the structures
  1304. from the application, allow version error checking, and also allow
  1305. the use of custom error handling routines during the initialization,
  1306. which the old functions do not.   The functions png_read_destroy() and
  1307. png_write_destroy() do not actually free the memory that libpng allocated
  1308. for these structs, but just reset the data structures, so they can be
  1309. used instead of png_destroy_read_struct() and png_destroy_write_struct()
  1310. if you feel there is too much system overhead allocating and freeing the
  1311. png_struct for each image read.
  1312.  
  1313. Setting the error callbacks via png_set_message_fn() before
  1314. png_read_init() as was suggested in libpng-0.88 is no longer supported
  1315. because this caused applications which do not use custom error functions
  1316. to fail if the png_ptr was not initialized to zero.  It is still possible
  1317. to set the error callbacks AFTER png_read_init(), or to change them with
  1318. png_set_error_fn(), which is essentially the same function, but with a
  1319. new name to force compilation errors with the new library.
  1320.  
  1321.